package com.example.demo.controller.rmw;

import com.example.demo.controller.rmw.dto.XxtSmsReq;
import com.example.demo.util.HttpClientUtils;
import com.example.demo.util.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class RmwSmsUtil {

    private static final Logger log = LoggerFactory.getLogger(RmwSmsUtil.class);
    private static String url = "https://swdxzdzh.cn:7443/receive/SMSController/sendSms";
    public static void main(String[] args) {
        XxtSmsReq req = new XxtSmsReq();
        req.setAuth_code("3705aba132fb65e5cf95e0956c4e93c6ac87c376");
        req.setSpid("111856");
        req.setExtport("");
        long timeStamp = System.currentTimeMillis();
        String smsId = "SEND15868854470_"+timeStamp;
        req.setSmsid(smsId);
        req.setMobiles("15868854470");
//        req.setContent("【人民网】本次登录验证码为1234562");
        String template = "【人民网】本次登录验证码为%s，%s分钟内有效，如非本人操作请忽略本短信";

        String text = String.format(template, "123456", 1);
        req.setContent(text);

        req.setSendtime("");
        req.setTimestamp(System.currentTimeMillis()+"");
        String auth_key = "d10caeb1593356b7a8910af5d4ce057f";
        try {
            String sign = getSHA(req.getAuth_code() + req.getSpid() + req.getExtport() + req.getSmsid() + req.getMobiles() + req.getSendtime() + URLEncoder.encode(req.getContent(), "utf-8") + req.getTimestamp() + auth_key);
            req.setSign(sign);
            String json = JsonUtil.toJson(req);
            log.info("短信发送请求参数url:{},params:{}",url,json);
            String response = HttpClientUtils.postJson(url, json);
            log.info("短信发送返回值response：{}",response);
        } catch (UnsupportedEncodingException ue) {
            log.error("签名失败：{}",ue.getMessage());
        }

    }

    public static String getSHA(String str) {
        try {
            MessageDigest digest = MessageDigest
                    .getInstance("SHA");
            digest.update(str.getBytes());
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }
}
